<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>登录</title>
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <legend>登录</legend>
      <div class="form-group">
        <label for="">用户名</label>
        <input
          type="text"
          class="form-control"
          id="username"
          placeholder="请输入用户名"
        />
      </div>
      <div class="form-group">
        <label for="">密码</label>
        <input
          type="text"
          class="form-control"
          id="password"
          placeholder="请输入密码"
        />
      </div>
      <button type="submit" class="btn btn-primary">登录</button>
      <a href="/register" class="btn btn-danger">还没有账号，去注册</a>
    </div>
    <script>
      $("button").click(function () {
        let username = $("#username").val();
        let password = $("#password").val();
        $.ajax({
          url: "/doLogin",
          type: "post",
          data: {
            username: username,
            password: password,
          },
          success: function (res) {
            console.log(res);
            alert(res.msg);
            if (res.code == 200) {
              //登录成功，就把此用户的_id(uid)和token存到本地缓存localStorage中
              localStorage.setItem("uid", res.users._id);
              localStorage.setItem("token", res.users.token);
              //登录成功跳转到首页
              location.href = "/index";
            }
          },
        });
      });
    </script>
  </body>
</html>
